package main

import (
	"MaterialIdentification/svc"
	"fmt"
	"github.com/gin-gonic/gin"
	uuid "github.com/satori/go.uuid"
	"net/http"
	"os"
	"slices"
)

func hasName(dir, target string) (bool, error) {
	readDir, err := os.ReadDir(dir)
	if err != nil {
		return false, fmt.Errorf("读取文件夹失败: %w", err)
	}

	find := slices.ContainsFunc(readDir, func(entry os.DirEntry) bool {
		return entry.Name() == target
	})

	return find, nil
}

func Upload(context *gin.Context) {
	file1, _ := context.FormFile("origin")
	file2, _ := context.FormFile("result")
	userid := context.PostForm("id")

	var (
		id1 string
		id2 string
	)

	for {
		id1 = uuid.NewV4().String()
		has, err := hasName("./pictrues", fmt.Sprintf("%s%s", id1, file1.Filename))
		if err != nil {
			context.JSON(http.StatusOK, NewResp(1, "保存文件异常"))
			return
		}
		if has {
			continue
		}
		context.SaveUploadedFile(file1, "./pictrues/"+id1+file1.Filename)
		break
	}

	for {
		id2 = uuid.NewV4().String()
		has, err := hasName("./result", fmt.Sprintf("%s%s", id2, file2.Filename))
		if err != nil {
			context.JSON(http.StatusOK, NewResp(1, "保存文件异常"))
			return
		}
		if has {
			continue
		}
		context.SaveUploadedFile(file2, "./result/"+id2+file1.Filename)
		break
	}

	err := svc.Db.Model(&Logs{}).Where("id = ?", userid).Update("originpicture", id1+file1.Filename).Error
	if err != nil {
		context.JSON(http.StatusOK, NewResp(1, "数据库异常"))
		return
	}
	err = svc.Db.Model(&Logs{}).Where("id = ?", userid).Update("resultpicture", id2+file2.Filename).Error
	if err != nil {
		context.JSON(http.StatusOK, NewResp(1, "数据库异常"))
		return
	}

	context.JSON(http.StatusOK, NewResp(0, "文件上传成功"))
}
